package com.spring.web.adminmanage.controller;

import com.spring.web.adminmanage.common.PageResult;
import com.spring.web.adminmanage.entities.BaseVo;
import com.spring.web.adminmanage.entities.Role;
import com.spring.web.adminmanage.entities.User;
import com.spring.web.adminmanage.service.RoleService;
import com.spring.web.adminmanage.service.WebUserService;
import com.spring.web.adminmanage.utils.MenuUtil;
import com.spring.web.adminmanage.utils.SwordBCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 后台用户的controller
 * @author xiankejin
 * @date 2017-07-07
 */
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private WebUserService userService;
	@Autowired
	private RoleService roleService;
	
	/*@RequestMapping("/bindInterface")
	public String bindInterface(User user, Model model) {
		List<UserApiInterface> userApiInterfaceList =  apiInterfaceService.getApiInterfaceByUser(user);
		List<Long> selectApiInterfaceList = new ArrayList<>();
		for (UserApiInterface userApiInterface : userApiInterfaceList) {
			selectApiInterfaceList.add(userApiInterface.getApiInterface().getId());
		}
		List<ApiInterface> apiInterFaceList = apiInterfaceService.getAllApiInterface();
		UserApiInterface userApiInterface = new UserApiInterface();
		userApiInterface.setUserId(user.getId());
		model.addAttribute("selectApiInterfaceList", selectApiInterfaceList);
		model.addAttribute("apiInterFaceList", apiInterFaceList);
		model.addAttribute("userApiInterface", userApiInterface);
		return "user/bind_interface";
	}*/
	
	/**
	 * 跳转到锁定页面
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping("/lockStatusForm")
	public String golockStatusPage(User user, Model model) {
		User userbean = new User();
		if(user.getId()!=null) {
			userbean = userService.getUserById(user);
		}
		Role role = new Role();
		if(userbean.getRole()!=null) {
			role = userbean.getRole();
		}
		model.addAttribute("role", role);
		model.addAttribute("user", userbean);
		return "user/userLock_Form";
	}
	
	/**
	 * 删除后台用户
	 * @param user
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/del")
	public BaseVo deleteUser(User user, Model model) {
		BaseVo vo = new BaseVo("0", "操作失败");
		try {
			userService.delUser(user);
			vo.setCode("1");
			vo.setMsg("操作成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vo;
	}
	
	
	/**
	 * 重置密码
	 * @param user
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/resetPwd")
	public BaseVo resetPwd(User user, Model model) {
		BaseVo vo = new BaseVo("0", "操作失败");
		try {
			String resetPwd = userService.resetPwd(user);
			vo.setCode("1");
			vo.setMsg("重置后的密码："+resetPwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vo;
	}
	
	
	/**
	 * 新增或修改用户
	 * @param user
	 * @param result
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/add", method = RequestMethod.POST)
	public BaseVo add(@Valid User user, BindingResult result, Model model) {
		Boolean res = userService.checkUserName(user);
		BaseVo vo = new BaseVo("0", "操作失败");
		if(result.hasErrors() || res) {
			List<ObjectError> allErrors = result.getAllErrors();
			StringBuilder msgSb = new StringBuilder();
			if(res) {
				msgSb.append("用户名已存在<br/>");
			}
			for (ObjectError error : allErrors) {
				msgSb.append(error.getDefaultMessage()).append("<br/>");
			}
			vo.setMsg(msgSb.toString());
		}else {
			userService.operUser(user);
			vo.setCode("1");
			vo.setMsg("操作成功");
		}
		return vo;
	}
	
	/**
	 * 跳转到表单页面
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping("/form")
	public String goFormPage(User user, Model model) {
		User userbean = new User();
		if(user.getId()!=null) {
			userbean = userService.getUserById(user);
		}
		Role role = new Role();
		if(userbean.getRole()!=null) {
			role= userbean.getRole();
		}
		List<Role> roleList = roleService.selectAll();
		model.addAttribute("roleList", roleList);
		model.addAttribute("user", userbean);
		model.addAttribute("role", role);
		return "user/user_form";
	}
	
	/**
	 * 跳转到后台用户列表页面
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping("/admin")
	public String goAdminPage(HttpServletRequest request , User user, Model model) {
		MenuUtil.fmtMenu(request,"/user/admin");
		return "user/user_list";
	}
	
	
	/**
	 * 获取后台用户列表数据
	 * @param pageIndex
	 * @param pageSize
	 * @param model
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/list")
	public PageResult<User> list(@RequestParam("pageIndex") int pageIndex, @RequestParam("pageSize") int pageSize,
								 Model model, User user) {
		return userService.queryPageResult(pageIndex, pageSize, user);
	}
	
	/**
	 * 检查用户名是否存在
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/checkUsername")
	public BaseVo checkUserNameUnique(User user) {
		BaseVo vo = new BaseVo("0", "操作失败");
		Boolean result = userService.checkUserName(user);
		if(result) {//重复
			vo.setCode("1");
			vo.setMsg("操作成功");
		}
		return vo;
	}
	
	@RequestMapping("/modifyData")
	public String modifyData(HttpServletRequest request, Model model){
		User userdata = (User)request.getSession().getAttribute("loginUser");
		model.addAttribute("user", userdata);
		return "modifyData";
	}
	
	@RequestMapping("/updatapassword")
	public String updataPassword(HttpServletRequest request, String oldpassword, String newpassword,
                                 String repeatpassword, Model model){
		User userdata = (User)request.getSession().getAttribute("loginUser");
		userdata = userService.getUserByUsername(userdata);
		model.addAttribute("user", userdata);
		if (!SwordBCrypt.checkpw(userdata.getUsername()+oldpassword, userdata.getSysPwd())) {
			model.addAttribute("errmsg", "当前密码错误");
			return "modifyData";
		}
		model.addAttribute("oldpassword", oldpassword);
		if (newpassword==null||newpassword.length()<6) {
			model.addAttribute("errmsg", "密码长度不小于6位");
			return "modifyData";
		}
		if (!newpassword.equals(repeatpassword)) {
			model.addAttribute("errmsg", "两次输入的密码不一致");
			return "modifyData";
		}
		userdata.setSysPwd(newpassword);
		userService.updateUser(userdata);
		model.addAttribute("oldpassword", null);
		model.addAttribute("sucmsg", "修改成功");
		return "redirect:/index";
	}

	/**
	 * 查询用户信息
	 * @param request
	 * @param model
	 * @return
	 */
	@GetMapping("/details")
	public String details(HttpServletRequest request, Model model){
		MenuUtil.fmtMenu(request,"/user/details");
		User sessionUser = (User)request.getSession().getAttribute("loginUser");
		User user = userService.findUser(sessionUser);
		model.addAttribute("user",user);
		return "user/user_details";
	}

	/**
	 * 跳转用户信息修改页面
	 * @param request
	 * @param model
	 * @return
	 */
	@PostMapping("/update")
	public String updateKey(HttpServletRequest request, Model model){
		User sessionUser = (User)request.getSession().getAttribute("loginUser");
		User user = userService.getUserByUsername(sessionUser);
		model.addAttribute("user",user);
		return "user/user_details_form";
	}

	/**
	 * 修改用户信息
	 * @param user
	 * @return
	 */
	@ResponseBody
	@PostMapping("/implementUpdate")
	public BaseVo update(User user){
		BaseVo vo = new BaseVo("0", "操作失败");
		try {
			userService.updateUserById(user);
			vo.setCode("1");
			vo.setMsg("操作成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vo;
	}

}
